package com.song.rabbitmq.f_all;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * 完整的声明式创建方式
 *      代码声明交换机、以及交换机绑定的队列
 */
public class Consumer {
    private static Runnable runnable = () -> {
        // 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        // 设置连接属性
        connectionFactory.setHost("121.41.53.91");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        Connection connection = null;
        Channel channel = null;

        //获取队列的名称
        final String queueName = Thread.currentThread().getName();

        try {
            // 1.从连接工厂中获取连接
            connection = connectionFactory.newConnection("direct路由模式-消费者");
            // 2.从连接中获取通道channel
            channel = connection.createChannel();

            // 定义接受消息的回调
            Channel finalChannel = channel;


            finalChannel.basicConsume(
                    queueName,    //队列的名称
                    true,
                    new DeliverCallback() {
                        @Override
                        public void handle(String s, Delivery delivery) throws IOException {
                            System.out.println("DeliverCallback==>" + queueName + "：收到消息是：" + new String(delivery.getBody(), "UTF-8"));
                        }
                    },
                    new CancelCallback() {
                        @Override
                        public void handle(String s) throws IOException {
                            System.out.println("CancelCallback==>");
                        }
                    }
            );
            System.out.println(queueName + "：开始接受消息");
            System.in.read();
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("发送消息出现异常...");
        } finally {
            // 7: 释放连接关闭通道
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (connection != null && connection.isOpen()) {
                try {
                    connection.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    };


    public static void main(String[] args) {
        // 启动三个线程去执行,接收队列中的消息
        new Thread(runnable, "declare_queue1").start();
        new Thread(runnable, "declare_queue2").start();
        new Thread(runnable, "declare_queue3").start();

    }

}
